package com.ctg.platform.core.security;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.ibatis.SqlMapClientTemplate;
import org.springframework.security.providers.encoding.Md5PasswordEncoder;
import org.springframework.security.providers.encoding.PasswordEncoder;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;

import com.ctg.payroll2.bean.filter.sysadmin.RoleFilter;
import com.ctg.platform.core.SecurityConstants;
import com.ctg.platform.core.security.Exception.RoleNameException;
import com.ctg.platform.core.security.Exception.SecurityException;
import com.ctg.platform.core.security.entity.Account;
import com.ctg.platform.core.security.entity.Resource;
import com.ctg.platform.core.security.entity.Role;
import com.ctg.platform.core.security.entity.SysLogUser;
import com.ctg.platform.core.security.web.SecureResourceFilterInvocationDefinitionSource;
import com.ctg.platform.core.service.BaseBzServiceImpl;
import com.ctg.platform.orm.ibatis.IbatisEntityDao;
import com.ctg.platform.util.Page;
import com.ibatis.sqlmap.client.SqlMapClient;
/**
 * 权限接口实现
 * @author luli
 * @createdate 2009-8-6 上午11:37:51
 */
@SuppressWarnings({"unchecked", "unused"})
public class SpringSecurityManagerImpl extends BaseBzServiceImpl implements SpringSecurityManager, UserDetailsService {
	private Log logger = LogFactory.getLog(getClass());
	private static String SECURITY_NAMESPACE = "SpringSecurityManagerImpl";
	private static int DELETE = 1;
	private static int UPDATE = 2;
	private IbatisEntityDao ibatisEntityDao;
	
	/*private BaseBzService baseBzService;
	
	public void setBaseBzService(BaseBzService baseBzService) {
		this.baseBzService = baseBzService;
	}*/
	
	public Page getUserListByFilter(List<String> idList, String userName, String isDisabled, int startrow, int endrow){
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < idList.size(); i++) {
			String id = idList.get(i);
			sb.append("'").append(id).append("',");
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("ids", sb.substring(0, sb.length()-1));
		map.put("userName", userName);
		map.put("disabled", isDisabled);
		map.put("startIndex", startrow);
		map.put("endIndex", endrow);
		
		Page page = ibatisEntityDao.pagedQuery(this.getClass(), map, startrow, endrow, ".getUserListByFilter_count", ".getUserListByFilter_query");
		return null;
	}
	
	public static void main(String[] args) throws ClassNotFoundException {
	}

	public Page getRoleList(int startrow, int endrow) {
		Map<String, Integer> map = new HashMap<String, Integer>();
		map.put("startIndex", startrow);
		map.put("endIndex", endrow);
		
		Page page = ibatisEntityDao.pagedQuery(this.getClass(),map,startrow,endrow);
		return page;
	}
	
	public Page getRoleListByFilter(RoleFilter filter) {
		Page page = ibatisEntityDao.pagedQueryByFilter(this.getClass(), filter);
		return page;
	}
	
	public Map<String, String> loadUrlAuthorities(String productType) {
		Map<String, String> urlAuthorities = new HashMap<String, String> ();
        List<Resource> urlResources = null;
		try {
			urlResources = getLocalSqlMapClient().queryForList(SECURITY_NAMESPACE+".getResource");
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
        for (Resource resource : urlResources) {
            urlAuthorities.put(resource.getValue(), resource.getRoleAuthorities());
        }
        return urlAuthorities;
	}

	public UserDetails loadUserByUsername(String userName)
			throws UsernameNotFoundException, DataAccessException {
		List<Account> users = null;
		//加密用户名
		//PasswordEncoder psw = new Md5PasswordEncoder();
		//String encoderUserName = psw.encodePassword(userName, null);
		try {
			users = getLocalSqlMapClient().
				queryForList(SECURITY_NAMESPACE+".getUsersByUserName", userName);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
        if (users.isEmpty()) {
        	logger.debug("根据密码查找用户未找到!");
            throw new UsernameNotFoundException("User " 
            		+ userName + " has no GrantedAuthority");
        }
        //users.get(0).setUsername(userName);//将未加密的用户名保存到user中
        return users.get(0);
	}
	
	public List<Account> getUserListByFilter(String userName, String isDisabled){
		Map<String, String> map = new HashMap<String, String>();
		map.put("userName", userName);
		map.put("disabled", isDisabled);
		
		List<Account> list = new ArrayList<Account>();
		try {
			list = getLocalSqlMapClient().queryForList(SECURITY_NAMESPACE+".getUserListByFilter", map);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
		return list;
	}

	public List<String> loadProductTypeList() {
		List<String> list = new ArrayList < String > ();
		try {
			list = getLocalSqlMapClient()
					.queryForList(SECURITY_NAMESPACE+".loadProductTypeList");
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
		return list;
	}
	
	public boolean assignPrivilegeForRole2(String roleId, String[] privileges, SysLogUser sysLogUser){
		try {
			getLocalSqlMapClient().startTransaction();
			getLocalSqlMapClient().delete(SECURITY_NAMESPACE+".revokeAllPrivilegeFromRole", roleId);
			getLocalSqlMapClient().startBatch();
			for (int i = 0; i < privileges.length; i++) {
				Map<String, String> map = new HashMap<String, String>();
				map.put("roleId", roleId);
				map.put("privilegeId", privileges[i]);
				getLocalSqlMapClient().insert(SECURITY_NAMESPACE+".assignPrivilegeForRole", map);
			}
			getLocalSqlMapClient().executeBatch();
			getLocalSqlMapClient().commitTransaction();
		}catch(SQLException e){
			e.printStackTrace();
			return false;
		}
		finally {
			try {
				getLocalSqlMapClient().endTransaction();
			} catch (SQLException e) {
				e.printStackTrace();
				return false;
			}
		}
		logger.debug("用户<"+sysLogUser.getUsername()+">对角色分配权限操作成功!");
		setAuthoritiesChanged();
		return true;
	}
	

	public boolean assignPrivilegeForRole(String roleId, String[] privileges,
			SysLogUser sysLogUser){
		try {
			getLocalSqlMapClient().startTransaction();
			getLocalSqlMapClient().startBatch();
			for (int i = 0; i < privileges.length; i++) {
				Map<String, String> map = new HashMap<String, String>();
				map.put("roleId", roleId);
				map.put("privilegeId", privileges[i]);
				getLocalSqlMapClient().insert(SECURITY_NAMESPACE+".assignPrivilegeForRole", map);
			}
			getLocalSqlMapClient().executeBatch();
			getLocalSqlMapClient().commitTransaction();
		}catch(SQLException e){
			e.printStackTrace();
			return false;
		}
		finally {
			try {
				getLocalSqlMapClient().endTransaction();
			} catch (SQLException e) {
				e.printStackTrace();
				return false;
			}
		}
		logger.debug("用户<"+sysLogUser.getUsername()+">对角色分配权限操作成功!");
		setAuthoritiesChanged();
		return true;
	}

	public boolean assignRoleForAccount(Account account, String[] roleIds,
			SysLogUser sysLogUser) {
		try {
			getLocalSqlMapClient().startTransaction();
			getLocalSqlMapClient().startBatch();
			for (int i = 0; i < roleIds.length; i++) {
				Map<String, String> map = new HashMap<String, String>();
				map.put("accountId", account.getId());
				map.put("roleId", roleIds[i]);
				getLocalSqlMapClient().insert(SECURITY_NAMESPACE+".assignRoleForAccount", map);
			}
			getLocalSqlMapClient().executeBatch();
			getLocalSqlMapClient().commitTransaction();
		} catch(SQLException e){
			e.printStackTrace();
			return false;
		} finally {
			try {
				getLocalSqlMapClient().endTransaction();
			} catch (SQLException e) {
				e.printStackTrace();
				return false;
			}
		}
		logger.debug("用户<"+sysLogUser.getUsername()+">对账户分配角色操作成功!");
		setAuthoritiesChanged();
		return true;
	}
	
	public Account createSysAccountAndGet(Account account, SysLogUser sysLogUser) throws SecurityException{
		if(account==null)
			return null;
		String id = sysUtilManager.getGUID();
		logger.debug("GUID="+id);
		account.setId(id);
		createSysAccount(account, sysLogUser);
		
		return (Account)getAccountByAccountId(id, sysLogUser);
	}

	public int createSysAccount(Account account, SysLogUser sysLogUser) throws SecurityException{
		if(account==null)
			return 0;
		if(getAccountByUserName(account.getUsername())!=null){
			throw new SecurityException("The user name:"+account.getUsername()+" has exists!");
		}
		if(StringUtils.isEmpty(account.getId())){
			account.setId(sysUtilManager.getGUID());
			logger.debug("GUID="+account.getId());
		}
		PasswordEncoder pe = new Md5PasswordEncoder();
		if (StringUtils.isEmpty(account.getPassword())) {
			account.setPassword(pe.encodePassword(SecurityConstants.DEFAULT_PASSWORD, account.getUsername()));
		}else{
			account.setPassword(pe.encodePassword(account.getPassword(), account.getUsername()));
		}
		try {
			getLocalSqlMapClient().insert(SECURITY_NAMESPACE+".createSysAccount", account);
		} catch (SQLException e) {
			e.printStackTrace();
			return 0;
		}
		logger.debug("用户<"+sysLogUser.getUsername()+">创建账户<"+account.getUsername()+">操作成功!");
		return 1;
	}

	public String createSysResource(Resource res, SysLogUser sysLogUser){
		if(res==null)
			return null;
		if(StringUtils.isEmpty(res.getId())){
			res.setId(sysUtilManager.getGUID());
			logger.debug("GUID="+res.getId());
		}		try {
			getLocalSqlMapClient().insert(SECURITY_NAMESPACE+".createSysResource", res);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
		
		logger.debug("用户<"+sysLogUser.getUsername()+">创建资源<"+res.getValue()+">操作成功!");
		return res.getId();
		
	}

	public String createSysRole(Role role, SysLogUser sysLogUser) throws SecurityException, RoleNameException{
		if(getRoleByRoleName(role.getName(), true)!=null){
			throw new SecurityException("The role name:"+role.getName()+" has exists!");
		}
		if (role==null||StringUtils.isEmpty(role.getName())) {
			return null;
		}
		
		if(StringUtils.isEmpty(role.getId())){
			role.setId(sysUtilManager.getGUID());
			logger.debug("GUID="+role.getId());
		}
		role.setName(SecurityUitls.buildRoleName(role.getName()));
		
		int i = 0;
		Integer I = null;
		try {
			I = (Integer)getLocalSqlMapClient().insert(SECURITY_NAMESPACE+".createSysRole", role);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
		if(I==null)
			return role.getId();
		else{
			logger.debug("用户<"+sysLogUser.getUsername()+">创建角色<"+role.getName()+">操作成功!");
			return role.getId();
		}
	}

	public boolean deleteAccountById(String[] accountId, SysLogUser sysLogUser){
		boolean b = commonOperation(accountId, "deleteAccountById", DELETE);
		
		if(b){
			logger.debug("用户<"+sysLogUser.getUsername()+">删除账户操作成功!");
		}
		return b;
	}
	
	public boolean deletePrivilegesById(String[] privilegeId, SysLogUser sysLogUser){
		boolean b = commonOperation(privilegeId, "deletePrivilegesById", DELETE);
		
		if(b){
			logger.debug("用户<"+sysLogUser.getUsername()+">删除权限操作成功!");
		}
		return b;
	}

	public boolean deleteRoleById(String[] roleId, SysLogUser sysLogUser){
		boolean b = commonOperation(roleId, "deleteRoleById", DELETE);
		
		if(b){
			logger.debug("用户<"+sysLogUser.getUsername()+">删除角色操作成功!");
		}
		return b;
	}

	public boolean freezeAccount(String[] accountId, SysLogUser sysLogUser){
		boolean b = commonOperation(accountId, "freezeAccount", UPDATE);
		
		if(b){
			logger.debug("用户<"+sysLogUser.getUsername()+">冻结账户操作成功!");
		}
		setAuthoritiesChanged();
		return b;
	}
	
	public boolean unfreezeAccount(String[] accountId, SysLogUser sysLogUser){
		boolean b = commonOperation(accountId, "unfreezeAccount", UPDATE);
		
		if(b){
			logger.debug("用户<"+sysLogUser.getUsername()+">解冻账户操作成功!");
		}
		setAuthoritiesChanged();
		return b;
	}
	
	public boolean freezeRole(String[] roleId, SysLogUser sysLogUser){
		boolean b = commonOperation(roleId, "freezeRole", UPDATE);
		
		if(b){
			logger.debug("用户<"+sysLogUser.getUsername()+">冻结角色操作成功!");
		}
		setAuthoritiesChanged();
		return b;
	}
	
	public boolean unfreezeRole(String[] roleId, SysLogUser sysLogUser){
		boolean b = commonOperation(roleId, "unfreezeRole", UPDATE);
		
		if(b){
			logger.debug("用户<"+sysLogUser.getUsername()+">解冻角色操作成功!");
		}
		setAuthoritiesChanged();
		return b;
	}

	public boolean freezePrivileges(String[] privilegeId, SysLogUser sysLogUser){
		boolean b = commonOperation(privilegeId, "freezePrivileges", UPDATE);
		
		if(b){
			logger.debug("用户<"+sysLogUser.getUsername()+">冻结权限操作成功!");
		}
		setAuthoritiesChanged();
		return b;
	}
	
	public boolean unfreezePrivileges(String[] privilegeId, SysLogUser sysLogUser){
		boolean b = commonOperation(privilegeId, "unfreezePrivileges", UPDATE);
		
		if(b){
			logger.debug("用户<"+sysLogUser.getUsername()+">解冻权限操作成功!");
		}
		setAuthoritiesChanged();
		return b;
	}

	public List<Resource> getPrivilegesByAccountId(String accountId,
			SysLogUser sysLogUser){
		List<Resource> list = new ArrayList<Resource>();
		try {
			list = getLocalSqlMapClient()
				.queryForList(SECURITY_NAMESPACE+".getPrivilegesByAccountId", accountId);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
		return list;
	}

	public List<Resource> getPrivilegesByLoginName(String logName, 
			SysLogUser sysLogUser){
		//PasswordEncoder pe = new Md5PasswordEncoder();
		//logName = pe.encodePassword(logName, null);
		List<Resource> list = new ArrayList<Resource>();
		try {
			list = getLocalSqlMapClient()
				.queryForList(SECURITY_NAMESPACE+".getPrivilegesByLoginName", logName);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
		return list;
	}
	
	public List<Resource> getAllPrivilegesByRoleId(String roleId, SysLogUser sysLogUser){
		return getPrivilegeByRoleId(roleId, true);
	}
	/**
	 * 根据roleid查找其权限列表
	 * @param roleId 角色id
	 * @param flag 是否查找已经冻结的(true:查;false:不查)
	 * @return
	 */
	private List<Resource> getPrivilegeByRoleId(String roleId, boolean flag){
		List<Resource> list = new ArrayList<Resource>();
		
		Map<String, String> map = new HashMap<String, String>();
		map.put("roleId", roleId);
		if (!flag) {
			map.put("roleDisabled", "0");
			map.put("resDisabled", "0");
		}
		
		list = getLocalSqlMapClientTemplate().queryForList(SECURITY_NAMESPACE+".getPrivilegesByRoleId", map);
		return list;
	}
	
	public List<Resource> getPrivilegesByRoleId(String roleId,
			SysLogUser sysLogUser){
		return getPrivilegeByRoleId(roleId, false);
	}

	public Account getAccountByAccountId(String accountId, SysLogUser sysLogUser) {
		Account account = new Account();
		try {
			account = (Account)getLocalSqlMapClient()
				.queryForObject(SECURITY_NAMESPACE+".getAccountByAccountId", accountId);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
		return account;
	}
	
	private Account getAccountByUserName(String userName){
		Account account = new Account();
		try {
			account = (Account)getLocalSqlMapClient()
				.queryForObject(SECURITY_NAMESPACE+".getAccountByUserName", userName);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
		return account;
	}
	
	public Account getAccountByUserName(String userName, SysLogUser sysLogUser) {
		return getAccountByUserName(userName);
	}

	public Role getRoleByRoleId(String roleId, SysLogUser sysLogUser){
		Role role = new Role();
		try {
			role = (Role)getLocalSqlMapClient()
				.queryForObject(SECURITY_NAMESPACE+".getRoleByRoleId", roleId);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
		return role;
	}
	public boolean changePasswordByUsername(String userName, String oldPassword,
			String newPassword, SysLogUser sysLogUser){
		if(StringUtils.isEmpty(userName)&&StringUtils.isEmpty(oldPassword)&&StringUtils.isEmpty(newPassword)){
			return false;
		}
		return changePasswordByUsernameAndId(userName, null, oldPassword, newPassword, sysLogUser);
	}
	
	public boolean changePasswordByUsernameAndId(String userName, String accountId, String oldPassword,
			String newPassword, SysLogUser sysLogUser){
//		String contextUserName = (String)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//		if (contextUserName==null) {
//			throw new UsernameNotFoundException("Can not find current user in session, make sure you have login!");
//		}
		PasswordEncoder pe = new Md5PasswordEncoder();
		oldPassword = pe.encodePassword(oldPassword, userName);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("oldPassword", oldPassword);
		map.put("accountId", accountId);
		map.put("userName", userName);
		Account user;
		try {
			user = (Account)getLocalSqlMapClient().queryForObject(SECURITY_NAMESPACE+".getUserByPasswordAndId",map);
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
		if (user==null) {
			throw new UsernameNotFoundException(SecurityConstants.USER_NOTEXITSTS);
		}else{
			map.put("newPassword", pe.encodePassword(newPassword, userName));
			try {
				getLocalSqlMapClient().update(SECURITY_NAMESPACE+".changePassword", map);
			} catch (SQLException e) {
				e.printStackTrace();
				return false;
			}
			logger.debug("用户修改密码成功!");
			return true;
		}
	}

	public boolean revokePrivilegeFromRole(String roleId, String[] privileges,
			SysLogUser sysLogUser){
		if(privileges.length==0)
			return false;
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("roleId", roleId);
		map.put("ids", SecurityUitls.parseIntarraytoStr(privileges, ","));
		
		try {
			getLocalSqlMapClient().delete(SECURITY_NAMESPACE+".revokePrivilegeFromRole", map);
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
		setAuthoritiesChanged();
		logger.debug("对角色<"+roleId+">收回权限成功!");
		return true;
	}
	
	public boolean revokeRoleFromAccount(String accountid, String[] roleIds,
			SysLogUser sysLogUser){
		if(roleIds.length==0)
			return false;
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("accountId", accountid);
		map.put("ids", SecurityUitls.parseIntarraytoStr(roleIds, ","));
		try {
			getLocalSqlMapClient().delete(SECURITY_NAMESPACE+".revokeRoleFromAccount", map);
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
		setAuthoritiesChanged();
		logger.debug("对账户<"+accountid+">收回角色成功!");
		return true;
	}
	
	public boolean revokeRoleFromAccount(String accountId, SysLogUser sysLogUser){
		if(accountId==null)
			return false;
		try {
			getLocalSqlMapClient().delete(SECURITY_NAMESPACE+".clearRoleFromAccount", accountId);
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
		setAuthoritiesChanged();
		logger.debug("对账户<"+accountId+">收回角色成功!");
		return true;
	}
	
	public List<Account> getAccountListByRoleId(String roleId){
		List<Account> list = new ArrayList<Account>();
		try {
			list = getLocalSqlMapClient().queryForList(SECURITY_NAMESPACE+".getAccountListByRoleId", roleId);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
		return list;
	}
	
	public boolean updateResource(Resource resource){
		try {
			getLocalSqlMapClient().update(SECURITY_NAMESPACE + ".updateResource",resource);
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	public boolean updateRole(Role role) throws RoleNameException{
		if(role==null||StringUtils.isEmpty(role.getName())){
			return false;
		}else{
			role.setName(SecurityUitls.buildRoleName(role.getName()));
		}
		int i = 0;
		try {
			i = getLocalSqlMapClient().update(SECURITY_NAMESPACE + ".updateRole", role);
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
		return i==1;
	}
	
	public List<Resource> getPrivilegesByPrivilegeIds(String[] ids){
		List<Resource> list = new ArrayList<Resource>();
		try {
			String s = SecurityUitls.parseIntarraytoStr(ids, ",");
			if(!StringUtils.isEmpty(s))
				list = getLocalSqlMapClient().queryForList(SECURITY_NAMESPACE+".getPrivilegesByPrivilegeIds", s);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}
	
	public Page getPrivilegesPageByPrivilegeIds(String[] ids){
		Page page = new Page();
			String s = SecurityUitls.parseIntarraytoStr(ids, ",");
			if(!StringUtils.isEmpty(s)){
				Map<String, Object> map = new HashMap<String, Object>();
				int startrow = 0;
				int endrow = 100000;
				map.put("ids", s);
				map.put("startIndex", startrow);
				map.put("endIndex", endrow);
				
				page = ibatisEntityDao.pagedQuery(this.getClass(), map, startrow, endrow, ".getPrivilegesPageByPrivilegeIds_count", ".getPrivilegesPageByPrivilegeIds_query");
			}
		
		return page;
	}
	
	public List<Role> getRoleListByLoginName(String name){
		List<Role> list = new ArrayList<Role>();
		if(StringUtils.isEmpty(name)){
			return list;
		}
		try {
			list = getLocalSqlMapClient().queryForList(SECURITY_NAMESPACE+".getRoleListByLoginName",name);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return list;
	}
	
	public Role getRoleByRoleName(String roleName, boolean flag){
		if (StringUtils.isEmpty(roleName)) {
			return null;
		}
		Role role = new Role();
		try {
			roleName = flag?SecurityUitls.buildRoleName(roleName):roleName;
		} catch (RoleNameException e1) {
			e1.printStackTrace();
		}
		try {
			role = (Role)getLocalSqlMapClient().queryForObject(SECURITY_NAMESPACE+".getRoleByRoleName", roleName);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return role;
	}
	
	public boolean revokeAllPrivilegeFromRole(String roleId, SysLogUser sysLogUser){
		if (StringUtils.isEmpty(roleId)) {
			return false;
		}
		try {
			getLocalSqlMapClient().delete(SECURITY_NAMESPACE+".revokeAllPrivilegeFromRole", roleId);
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	/**
	 * @param ibatisEntityDao 设置ibatisEntityDao
	 */
	public void setIbatisEntityDao(IbatisEntityDao ibatisEntityDao) {
		this.ibatisEntityDao = ibatisEntityDao;
	}
	
	/**
	 * 对于传入int数组的通用删除操作
	 * @param ids 操作的主键数组
	 * @param statement 执行SQL的statement
	 * @param operation 操作类别
	 * @return 操作是否成功
	 */
	private boolean commonOperation(String[] ids, String statement, int operation){
		try {
			getLocalSqlMapClient().startTransaction();
		switch (operation) {
			case 1:
				//删除角色时比较特殊,需要将两张关系表中的数据删除
				if(statement.equals("deleteRoleById")){
					getLocalSqlMapClient()
						.delete(SECURITY_NAMESPACE+".deleteUserRoleRefByRoleId", SecurityUitls.parseIntarraytoStr(ids, ","));
					getLocalSqlMapClient()
					.delete(SECURITY_NAMESPACE+".deleteRoleResourceRefByRoleId", SecurityUitls.parseIntarraytoStr(ids, ","));
					
				}else{
					getLocalSqlMapClient()
						.delete(SECURITY_NAMESPACE+"."+statement+"Ref", SecurityUitls.parseIntarraytoStr(ids, ","));
				}
				getLocalSqlMapClient()
					.delete(SECURITY_NAMESPACE+"."+statement, SecurityUitls.parseIntarraytoStr(ids, ","));
				break;
			case 2:
				getLocalSqlMapClient().startBatch();
				String flag = "1";
				if(statement.substring(0,2).equals("un")){
					flag = "0";
					statement = statement.substring(2,statement.length());
				}
				for (int i = 0; i < ids.length; i++) {
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("flag", flag);
					map.put("id", ids[i]);
					getLocalSqlMapClient().update(SECURITY_NAMESPACE+"."+statement, map);
				}
				getLocalSqlMapClient().executeBatch();
				break;
			default:
				break;
			}
			getLocalSqlMapClient().commitTransaction();
		} catch(SQLException e){
			e.printStackTrace();
			return false;
		} finally {
			try {
				getLocalSqlMapClient().endTransaction();
			} catch (SQLException e) {
				e.printStackTrace();
				return false;
			}
		}
		
		return true;
	}
	/**
	 * 设置需要刷新权限
	 */
	private void setAuthoritiesChanged(){
		SecureResourceFilterInvocationDefinitionSource.ischanged=true;
	}
	
	private SqlMapClient getLocalSqlMapClient(){
		return ibatisEntityDao.getSqlMapClient();
	}
	
	private SqlMapClientTemplate getLocalSqlMapClientTemplate(){
		return ibatisEntityDao.getSqlMapClientTemplate();
	}
}
